import {
  Controller,
  Get,
  Post,
  Body,
  Param,
  Put,
  Delete,
  Query,
  UseGuards,
  Request,
} from '@nestjs/common';
import { BookService } from './book.service';
import {
  CreateBookDto,
  UpdateBookDto,
  CreateBookCommentDto,
} from './dto/create-book.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';

import { ParseIntPipe } from '@nestjs/common';

@Controller('api/book')
export class BookController {
  constructor(private readonly bookService: BookService) {}

  @UseGuards(JwtAuthGuard)
  @Post()
  async create(@Body() createBookDto: CreateBookDto, @Request() req) {
    const book = await this.bookService.create(createBookDto, req.user.sub);
    return {
      code: 200,
      message: '发布成功',
      data: book,
    };
  }

  @Get('list')
  async findAll(@Query() query) {
    const [books, total] = await this.bookService.findAll(query);
    return {
      code: 200,
      message: '获取成功',
      data: {
        list: books,
        total,
      },
    };
  }

  // 新增模糊搜索接口
  @Get('search')
  async search(@Query() query) {
    const [books, total] = await this.bookService.findAll(query);
    return {
      code: 200,
      message: '搜索成功',
      data: {
        list: books,
        total,
      },
    };
  }

  @Get(':id')
  async findOne(@Param('id') id: string) {
    const book = await this.bookService.findOne(+id);
    return {
      code: 200,
      message: '获取成功',
      data: book,
    };
  }

  @UseGuards(JwtAuthGuard)
  @Put(':id')
  async update(
    @Param('id') id: string,
    @Body() updateBookDto: UpdateBookDto,
    @Request() req,
  ) {
    const book = await this.bookService.update(
      +id,
      updateBookDto,
      req.user.sub,
    );
    return {
      code: 200,
      message: '更新成功',
      data: book,
    };
  }

  @UseGuards(JwtAuthGuard)
  @Delete(':id')
  async remove(@Param('id') id: string, @Request() req) {
    await this.bookService.remove(+id, req.user.sub);
    return {
      code: 200,
      message: '删除成功',
    };
  }

  @UseGuards(JwtAuthGuard)
  @Post(':id/borrow')
  async borrow(@Param('id') id: string, @Request() req) {
    const book = await this.bookService.borrow(+id, req.user.sub);
    return {
      code: 200,
      message: '借阅成功',
      data: book,
    };
  }

  // 新增：预约图书接口
  @UseGuards(JwtAuthGuard)
  @Post(':id/reserve')
  async reserve(@Param('id') id: string, @Request() req) {
    const book = await this.bookService.reserve(+id, req.user.sub);
    return {
      code: 200,
      message: '预约成功',
      data: book,
    };
  }

  @UseGuards(JwtAuthGuard)
  @Post(':id/return')
  async return(@Param('id') id: string, @Request() req) {
    const book = await this.bookService.return(+id, req.user.sub);
    return {
      code: 200,
      message: '归还成功',
      data: book,
    };
  }

  @UseGuards(JwtAuthGuard)
  @Post(':id/comment')
  async createComment(
    @Param('id') id: string,
    @Body() createCommentDto: CreateBookCommentDto,
    @Request() req,
  ) {
    const comment = await this.bookService.createComment(
      +id,
      createCommentDto,
      req.user.sub,
    );
    return {
      code: 200,
      message: '评论成功',
      data: comment,
    };
  }

  @UseGuards(JwtAuthGuard)
  @Get('my-published')
  async getMyPublishedBooks(@Request() req) {
    const books = await this.bookService.getMyPublishedBooks(req.user.sub);
    return {
      code: 200,
      message: '获取成功',
      data: books,
    };
  }

  @UseGuards(JwtAuthGuard)
  @Get('my-borrowed')
  async getMyBorrowedBooks(@Request() req) {
    const books = await this.bookService.getMyBorrowedBooks(req.user.sub);
    return {
      code: 200,
      message: '获取成功',
      data: books,
    };
  }

  // 添加收藏（需要JWT认证）
  @UseGuards(JwtAuthGuard)
  @Post(':id/favorite')
  async addFavorite(
    @Param('id') bookId: string,
    @Request() req
  ) {
    const userId = req.user.sub; // 从JWT中获取用户ID
    await this.bookService.addFavorite(+userId, +bookId);
    return {
      code: 200,
      message: '收藏成功'
    };
  }

  // 取消收藏（需要JWT认证）
  @UseGuards(JwtAuthGuard)
  @Delete(':id/favorite')
  async removeFavorite(
    @Param('id') bookId: string,
    @Request() req
  ) {
    const userId = req.user.sub; // 从JWT中获取用户ID
    await this.bookService.removeFavorite(+userId, +bookId);
    return {
      code: 200,
      message: '取消收藏成功'
    };
  }

  // 新增：查询是否已收藏
  @UseGuards(JwtAuthGuard)
  @Get(':bookId/is-favorite')
  async checkIsFavorite(
    @Param('bookId', ParseIntPipe) bookId: number, // 强制转换为数字，失败时自动返回400错误
    @Request() req
  ) {
    const userId = +req.user.sub; // 确保userId是数字（JWT中的sub通常是字符串）
    const isFavorited = await this.bookService.isBookFavorited(userId, bookId);
    return {
      code: 200,
      message: '查询成功',
      data: isFavorited
    };
  }
}
